//
//  CustomerContact.m
//  Trading365
//
//  Created by Jason on 12-3-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CustomerContactList.h"
#import "CustomerContactCell.h"
#import "CustomerContactDetail.h"
#import "CustomerContactAdd.h"

@implementation CustomerContactList
@synthesize table;
@synthesize customer_id;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

//    [self.table initWithFrame:[UIScreen mainScreen].applicationFrame style:UITableViewStyleGrouped];
    self.title = INFO_STRING_CUSTOMER_CONTACT_LIST;

    //search,new
    UIToolbar* tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 80, 45)]; 
    UIImage* imageBar = [UIImage imageNamed:PIC_MAIL_TOP_BAR];    
    NSString* devVersion = [[UIDevice currentDevice] systemVersion];
    if ([devVersion compare:@"4.3.3"] == 0)
    {
        [tools respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)];
        [tools setTintColor:NAVIGATION_BAR_COLOR];
    }else
    {
        [tools setBackgroundImage:imageBar forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
    }
    
    NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:2];
    UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] 
                                      initWithBarButtonSystemItem:UIBarButtonSystemItemSearch
                                      target:self 
                                      action:@selector(find)];
    
    UIBarButtonItem *anotherButton1 = [[UIBarButtonItem alloc] 
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                       target:self 
                                       action:@selector(add)]; 
    
    [buttons addObject:anotherButton]; 
    [anotherButton release]; 
    [buttons addObject:anotherButton1]; 
    [anotherButton1 release]; 
    [tools setItems:buttons animated:NO]; 
    [buttons release]; 
    UIBarButtonItem *myBtn = [[UIBarButtonItem alloc] initWithCustomView:tools]; 
    self.navigationItem.rightBarButtonItem = myBtn;
    [myBtn release]; 
    [tools release];

    ///////
    
    self.table.backgroundColor = BACKGROUND_COLOR;
    [self refreshData];
    [self.table reloadData];

}

- (void)viewDidUnload
{
    [self setTable:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    ///////////////////////////
    if ([[InfoType share] GetFlagFreshView] == INFO_TYPE_VIEW_REFRESH){
//        NSLog(@"[[InfoType share] GetFlagFreshView]=%d",[[InfoType share] GetFlagFreshView]);
        [responseParams removeAllObjects];
        getflag = YES;
        [self refreshData];
        [self.table reloadData];
        [[InfoType share] SetFlagFreshView:INFO_TYPE_VIEW_NOFRESH];
    }
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [customer_id release];
    [table release];
    [super dealloc];
}

#pragma mark - Table view delegate
//Jason-子类需要复写该方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *tmp_dictionary=nil;//[[NSMutableDictionary alloc] initWithCapacity:0];
    if (indexPath.row < [responseParams count]){
        tmp_dictionary=[[NSMutableDictionary alloc] initWithDictionary:[responseParams objectAtIndex:indexPath.row]];
    }else{
        tmp_dictionary=[[NSMutableDictionary alloc] initWithCapacity:0];
    }

    NSString *p_name=[NSString stringWithFormat:@"%@",[tmp_dictionary valueForKey:@"contact_name"]];
//    NSString *p_id=[NSString stringWithFormat:@"%@",[tmp_dictionary valueForKey:@"id"]];
    
    CustomerContactDetail *detail = [[CustomerContactDetail alloc] init];
    [detail setContact_name:p_name];
    [detail setInfoDetail:tmp_dictionary];
    [self.navigationController pushViewController:detail animated:YES];
    
    [detail release];
    [tmp_dictionary release];
}

#pragma mark - Table view data source
//Jason-子类需要复写该方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *CellIdentifier = @"CustomerContactCell";
    
    CustomerContactCell* cell = (CustomerContactCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil){
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"CustomerContactCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
//    if (indexPath.row>[responseParams count]) {
//        return cell;
//    }
    
    NSUInteger row = [indexPath row];

    if ([responseParams count] <= row)
        return cell;

    NSMutableDictionary* dic = [[NSMutableDictionary alloc] initWithDictionary:[responseParams objectAtIndex:row]] ;
            
    cell.contactName.text=[dic objectForKey:@"contact_name"];
    NSString *tmp=[NSString stringWithFormat:@"%@",[dic objectForKey:@"mobile"]];
    if ([tmp length]<1)
        tmp=[NSString stringWithFormat:@"%@",[dic objectForKey:@"telphone"]];
    cell.contactTel.text=tmp;
    cell.contactMail.text=[dic objectForKey:@"mail"];
        
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.backgroundColor = [UIColor clearColor];
    cell.backgroundView.backgroundColor = [UIColor clearColor];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    [dic release];
    
    return cell;
}

#pragma mark - my fun

//Jason-子类需要复写该方法
- (void)doSearch{
    [super doSearch];
    //do something
    [table reloadData];
    [[[TaskManager Share] GetTaskByType:GetCustomerContactList Delegate:self] Excute];
}

//Jason-子类需要复写该方法
-(void)refreshData
{    
//    NSLog(@"InfoList refreshData.");
    [[[TaskManager Share] GetTaskByType:GetCustomerContactList Delegate:self] Excute];
}

//Jason-子类需要复写该方法
-(void) getMoreData
{
//    NSLog(@"InfoList getMoreData.");
    [[[TaskManager Share] GetTaskByType:GetCustomerContactList Delegate:self] Excute];
}

-(void) OnPreExcute
{
    [super OnPreExcute];
}

//Jason-子类需要复写该方法
-(void) DoInBackground
{
    if (getflag == NO && _isSearching == NO) {
        return;
    }
    startRow = [responseParams count];
    NSMutableArray *tmp=nil;
    XmlRpc *xml = [[XmlRpc alloc] init];
    
    //产品信息
    if (_isSearching){
//        tmp = [xml GetSearchCustContactList:userid position:@"5" searchWord:p_search startRows:num  rowsPerPage:rowsperpage];
    }else{
        tmp = [xml GetCustContractList:customer_id];
    }
        
    for (NSMutableDictionary* itq in tmp) {
        [responseParams addObject:itq];
    }
    
    if ([tmp count]<PER_PAGE_ROWS) {
        getflag = NO;
        _isSearching=NO;
    }
    
    [xml release];
    
    [table reloadData];
}

-(void) OnPostExcute
{    
    [super OnPostExcute];
}


-(void)add{
    //new contact
    CustomerContactAdd *contactAdd=[[CustomerContactAdd alloc] init];
    [contactAdd setParentID:self.customer_id];
    [self.navigationController pushViewController:contactAdd animated:YES];
    [contactAdd release];
}

@end
